package util

import (
	"context"
	"gorm.io/gorm/logger"
	"log"
	"time"
)

type GormLogger struct {
	SlowThreshold time.Duration
	LogLevel      logger.LogLevel
	Colorful      bool
}

// NewGormLogger 实例化日志配置
func NewGormLogger() *GormLogger {
	return &GormLogger{
		SlowThreshold: 3 * time.Second,
		LogLevel:      logger.Warn,
		Colorful:      true,
	}
}

// LogMode 实现GORM的Logger接口
func (l *GormLogger) LogMode(level logger.LogLevel) logger.Interface {
	return l
}

// Info 实现gorm模型的接口
func (l *GormLogger) Info(ctx context.Context, msg string, data ...interface{}) {
	Now := time.Now().Format("2006-01-02 15:04:05")
	log.Printf("[Info][%v]: %s | %v \n", Now, msg, data)
}

func (l *GormLogger) Warn(ctx context.Context, msg string, data ...interface{}) {
	Now := time.Now().Format("2006-01-02 15:04:05")
	log.Printf("[Warn][%v]: %s | %v \n", Now, msg, data)
}

func (l *GormLogger) Error(ctx context.Context, msg string, data ...interface{}) {
	Now := time.Now().Format("2006-01-02 15:04:05")
	log.Printf("[Error][%v]: %s | %v \n", Now, msg, data)
}

func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
	elapsed := time.Since(begin)
	sql, rows := fc()
	if err != nil {
		log.Printf("Error: %v\n", err)
	}
	if elapsed > l.SlowThreshold {
		log.Printf("[warn][slow query]: duration: %v, %d row affected,\n[sql]: %s;\n", elapsed, rows, sql)
	}
}
